import json
import os
import random
from django.shortcuts import render, redirect, reverse
from django.views.decorators.cache import cache_page
from area.models import Province
from user.models import *
from django.http import JsonResponse
from django.conf import settings
from django.core.mail import send_mail  # 发送邮箱
from django.core.cache import cache
from django.contrib.auth.hashers import make_password, check_password

if not settings.configured:
    settings.configure()


# 登录主页
def login_index(request):
    return render(request, "login.html")


# 生成邮箱验证码
def set_token():
    string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOBQRSTUVWXYZ0123456789"
    result = ""
    for i in range(6):
        result += random.choice(string)
    return result


# 发送邮件
def send_email(request):
    # 1935036485
    if request.method == "POST":
        result = {"statu": False}
        subject = "你好鱼客!"
        recipient_list = [request.POST.get("email")]
        password = request.POST.get("password")
        code = set_token()
        cache.set("code", code, 120)  # 两分钟缓存
        cache.set("num_code", 3, 120)  # 两分钟，三次机会
        if password:
            message = f"您的验证码为:{code}\n您设置的密码为{password}"
        else:
            user = UserModel.objects.filter(email=recipient_list[0])
            if not user.exists():
                return JsonResponse({"statu": False, "reason": "该邮箱未绑定，发送失败"})
            message = f"您的验证码为:{code}\n"
        print(message)
        sender = "2143667305@qq.com"
        if len(recipient_list) > 0:
            statu = send_mail(subject, message, sender, recipient_list)
            if statu == 1:
                result['statu'] = True
        return JsonResponse(result)


# 注册页
def sign_index(request):
    return render(request, "sign.html")


# 用户主页
def home_index(request):
    return render(request, "home.html")


# 管理员主页
def admin_index(request):
    return render(request, "admin.html")


def about(request):
    return render(request, "about.html")


# 修改资料
def update_user(request):
    if request.method == "POST":
        code = request.POST.get("code")
        user = UserModel.objects.filter(uid=request.POST.get("user_id")).first()
        # 如果有验证码则修改邮箱
        cache_code = cache.get("code")
        if cache_code:
            if cache_code == code:
                user.email = request.POST.get("email")
            else:
                return JsonResponse({"statu": False})
        user.nickname = request.POST.get("nickname")
        user.place_id = request.POST.get("place")
        # 如果缓存地图中有则删除地图分布缓存
        if cache.get("map_users") is not None:
            cache.delete("map_users")
        user.introduction = request.POST.get("introduction")
        user.save()
        return JsonResponse({"statu": True})


# 个人主页
def My_index(request, uid):
    cache_uid = cache.get("user_" + uid)
    if cache_uid == uid:
        user = UserModel.objects.filter(uid=uid).first()
        city = user.place

        if user:
            datas = {
                "user_id": uid,
                'username': user.username,
                'email': user.email,
                'nickname': user.nickname,
                'place': [city.provinceCode.code, city.code],
                'introduction': user.introduction,
                "img": user.img.url
            }

            return render(request, "userhome.html", {"datas": json.dumps(datas)})
    else:
        return JsonResponse({"statu": False, "reason": "用户未登录"})


# 登录
def login(request):
    if request.method == "POST":
        username = request.POST.get("username")
        user = UserModel.objects.filter(username=username)
        # 如果用户不存在
        if not user.exists():
            return JsonResponse({"statu": False, "reason": "没有该用户!"})
        user = user.first()
        datas = {
            "nickName": user.nickname,
            "user_id": user.uid,
            "img": user.img.url,
            "isadmin": user.isAdmin
        }
        password = request.POST.get("password")
        # 如果密码正确
        if check_password(password, user.password):
            cache.set(user.uid + "_statu", True, 10 * 60)  # 10分钟缓存
            cache.set("user_" + user.uid, user.uid, 60 * 10)  # 10分钟缓存
            return JsonResponse({"statu": True, "datas": datas})
        else:
            return JsonResponse({"statu": False, "reason": "密码错误!"})

    else:
        return redirect(reverse("login_index"))  # 重定向至登录页


# 注销
def exit_(request):
    uid = request.GET.get("uid")
    cache.delete("user_" + uid)  # 删除用户id
    cache.delete(uid + "_statu")  # 删除用户状态
    return JsonResponse({"statu": True})


def map_index(request):
    return render(request, "admin_map.html")


# 人数分布
def mapUser(request):
    try:
        cache_key = "map_users"  # 缓存键名
        # 从缓存获取数据
        redis_data = cache.get(cache_key)
        # 如果缓存中有数据，则直接返回
        if redis_data is not None:
            return JsonResponse({"statu": True, "datas": redis_data})
        datas = (
            Province.objects.annotate(count=models.Count("city__usermodel")).values("name", "count")
        )
        result = [
            {"name": item['name'], "value": item['count']}
            for item in datas
        ]
        cache.set(cache_key, result, 3600)  # 设置默认过期时间为1小时
        return JsonResponse({"statu": True, "datas": result})
    except Exception as e:
        print("user=>views=>mapUser", e)
        return JsonResponse({"statu": False})


# 注册
def sign(request):
    try:
        if request.method == "POST":
            rst = {"statu": False, "reason": ""}
            if request.method == "POST":
                username = request.POST.get("username")
                code = request.POST.get("code")
                cache_code = cache.get("code")
                cache_num = cache.get("num_code")
                if cache_code is None:
                    return JsonResponse({"statu": False, "reason": "验证码失效"})

                # 判断验证码
                if code != cache_code:
                    rst['reason'] = f"验证码有误,还有{cache_num}次机会"
                    cache_num -= 1
                    if cache_num == 0:
                        cache.delete("code")
                    else:
                        cache.set("num_code", cache_num, 120)
                    return JsonResponse(rst)

                # 账号是否存在
                u = UserModel.objects.filter(username=username)

                if u.exists():
                    rst['reason'] = "用户已存在"
                    return JsonResponse(rst)
                else:
                    password = request.POST.get("password")
                    user = UserModel(
                        username=username,
                        password=make_password(password),  # 加密
                        email=request.POST.get("email"),
                        nickname=request.POST.get("nickname"),
                        introduction=request.POST.get("introduction"),
                        place_id=request.POST.get("place")
                    )
                    user.save()  # 添加用户
                    rst['statu'] = True
            return JsonResponse(rst)
        else:
            return redirect(reverse("sign_index"))
    except Exception as e:
        print(request.POST)
        print(e)


# 忘记密码
def forget(request):
    try:
        print(request.POST)
        new_password = request.POST.get("pwd")
        code = request.POST.get("code")
        email = request.POST.get("email")
        user = UserModel.objects.filter(email=email)
        session_code = cache.get("code")
        if session_code is None:
            return JsonResponse({"statu": False, "reason": "验证码已过期"})
        if not user.exists():
            return JsonResponse({"statu": False, "reason": "该邮箱未绑定用户"})
        # # 如果验证码相同
        if session_code == code:
            user = user.first()
            print(user)
            user.password = make_password(new_password)
            user.save()
            return JsonResponse({"statu": True})
    except Exception as e:
        print("user=>views=>forget error", e)
        return JsonResponse({"statu": False, "reason": "后台bug，请联系工作人员"})


# 修改照片
def updateImg(request, uid):
    try:
        img = request.FILES.get("file")
        if img:
            user = UserModel.objects.filter(uid=uid).first()
            path = "uploads/" + user.img.name
            # 如果不是默认文件
            if uid in path:
                os.remove(path)
            type_ = img.name.split(".")[-1]
            img.name = uid + "." + type_  # 新照片
            user.img = img
            user.save()

        return JsonResponse({"statu": True})
    except Exception as e:
        print("updateImg error  ", e)
        return JsonResponse({"statu": False})


@cache_page(60 * 10)
def setStatu(request):
    uid = request.GET.get("uid")
    cache.set("user_" + uid, uid, 10 * 60)
    cache.set(uid + "_statu", True, 10 * 60)  # 10分钟缓存
    return JsonResponse({"statu": True, "datas": uid})
